package com.huaruan.youdi.views.fragments;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.view.menu.MenuItemImpl;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.huaruan.youdi.R;
import com.huaruan.youdi.utils.DeviceUtils;
import com.huaruan.youdi.views.IActivityHelper;
import com.huaruan.youdi.views.OnFastClickListener;

import butterknife.ButterKnife;

public abstract class BaseFragment extends Fragment implements IActivityHelper {
    private View containerView;
    private Toolbar toolbar;
    private TextView toolbarTitle;
    private Context context;
    private Handler handler;
    private View toolbarClose;
    MenuItemImpl messageMenuItem;
    private MenuItemImpl overFlowMenuItem;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        beforeSetContentView();
        setHasOptionsMenu(true);
        if (containerView == null) {
            if (IGetMultiSatesContentViewResId() != 0) {
                View rootView = View.inflate(IGetContext(), R.layout.base_multistate_layout, null);
                ((ViewGroup) rootView.findViewById(R.id.content)).addView(View.inflate(IGetContext(), IGetMultiSatesContentViewResId(), null));
                containerView = rootView;
            } else if (IGetContentView() != null) {
                containerView = IGetContentView();
            } else if (IGetContentViewResId() != 0) {
                containerView = inflater.inflate(IGetContentViewResId(), container, false);
            }
            ButterKnife.bind(this, containerView);
            View view = containerView.findViewById(R.id.toolbar);
            View title = containerView.findViewById(R.id.toolbarTitle);
            View close = containerView.findViewById(R.id.toolbarClose);
            if (view != null) {
                toolbar = (Toolbar) view;
                initToolbar(toolbar);
            }
            if (title != null) {
                toolbarTitle = (TextView) title;
                initToolbarTitle(toolbarTitle);
            }
            if (close != null) {
                toolbarClose = close;
                initToolbarClose(toolbarClose);
            }
        }
        return containerView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getActivity() == null || getActivity().isFinishing() || !isAdded() || isDetached()) {
            return;
        }
        IFindViews(containerView);
        IInitData();
        IRequest();
    }

    public void initToolbarClose(View close) {
        if (close == null)
            return;
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getActivity() != null && !getActivity().isFinishing())
                    getActivity().finish();
            }
        });
    }

    public void initToolbarTitle(TextView toolbarTitle) {
        if (toolbarTitle == null)
            return;
        if (isAdded())
            toolbarTitle.setText(getActivity().getTitle());
    }

    public void initToolbar(Toolbar toolbar) {
        if (toolbar == null)
            return;
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
//                if (item.getItemId() == R.id.home)
//                    AppUtils.JumpToHome(IGetActivity());
//                else if (item.getItemId() == R.id.center) {
//                    Intent toCenter = new Intent(IGetContext(), MainActivity.class);
//                    toCenter.putExtra("to", "center");
//                    toCenter.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    startActivity(toCenter);
//                } else if (item.getItemId() == R.id.message) {
//                    AppUtils.JumpToMessagePage(IGetContext(), null);
//                } else
                    onItemClick(item);
                return true;
            }
        });
        if (isShowBackButton()) {
            toolbar.setNavigationIcon(R.mipmap.ic_action_previous_item_black);
            toolbar.setNavigationOnClickListener(new OnFastClickListener() {
                @Override
                public void onFastClick(View v) {
                    onBackClicked();
                }
            });
        }
        initToolbarRightMenu();
    }

    public void onBackClicked() {
        try {
            if (getActivity() == null || getActivity().isFinishing())
                return;
            getActivity().onBackPressed();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void modifyToolbar(Toolbar toolbar) {
        toolbar.getLayoutParams().height = DeviceUtils.dp2px(48);
        toolbar.setBackgroundColor(Color.parseColor("#ffc01e2f"));
    }

    public void beforeSetContentView() {

    }

    /**
     * 初始化导航菜单栏
     */
    public void initToolbarRightMenu() {
        if (toolbar == null)
            return;
        if (!isShowDefaultOverflowMenu())
            return;
        toolbar.inflateMenu(R.menu.toolbar_right_menu);
        overFlowMenuItem = (MenuItemImpl) toolbar.getMenu().findItem(R.id.overFlow);
        messageMenuItem = (MenuItemImpl) getToolbar().getMenu().findItem(R.id.message);
    }

    /**
     * toolbar menu 其他item点击处理
     *
     * @param item
     */
    public void onItemClick(MenuItem item) {

    }

    @Override
    public Context IGetContext() {
        return context;
    }

    @Override
    public Activity IGetActivity() {
        return getActivity();
    }

    /**
     * 多状态基类布局，比如内容加载等待状态，数据请求失败状态等等。。。
     *
     * @return
     */
    @Override
    public int IGetMultiSatesContentViewResId() {
        return 0;
    }

    @Override
    public abstract int IGetContentViewResId();

    @Override
    public View IGetContentView() {
        return null;
    }

    @Override
    public void IFindViews() {

    }

    @Override
    public abstract void IFindViews(View view);

    @Override
    public abstract void IInitData();

    @Override
    public void IRequest() {
        showContentLoadingView();
    }

    @Override
    public void lazyLoad() {

    }

    public View getContainerView() {
        return containerView;
    }

    public void setToolbar(Toolbar toolbar) {
        this.toolbar = toolbar;
    }

    public Toolbar getToolbar() {
        return toolbar;
    }

    public TextView getToolbarTitle() {
        return toolbarTitle;
    }

    public View getToolbarClose() {
        return toolbarClose;
    }

    /**
     * 默认显示页面overflow menu,并且显示默认的item menu
     *
     * @return
     */
    public boolean isShowDefaultOverflowMenu() {
        return false;
    }

    /**
     * 是否显示页面后退键,默认不显示
     *
     * @return
     */
    public boolean isShowBackButton() {
        return false;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ViewGroup parent = (ViewGroup) containerView.getParent();
        if (parent != null) {
            parent.removeView(containerView);
        }
    }

    /**
     * 移除消息菜单栏
     */
    public void removeMessageMenuItem() {
        if (toolbar == null || toolbar.getMenu().size() == 0 || toolbar.getMenu().findItem(R.id.overFlow) == null)
            return;
        toolbar.getMenu().findItem(R.id.overFlow).setIcon(R.mipmap.ic_action_overflow);
        if (toolbar.getMenu().getItem(0).getSubMenu().findItem(R.id.message) != null)
            toolbar.getMenu().getItem(0).getSubMenu().removeItem(R.id.message);
        messageMenuItem = null;
    }


    public Handler getHandler() {
        if (handler == null)
            handler = new Handler(Looper.getMainLooper());
        return handler;
    }

    /**
     * 显示内容正在加载，全屏的
     */
    public void showContentLoadingView() {
        if (getContainerView() != null && getContainerView().findViewById(R.id.shloading) != null)
            getContainerView().findViewById(R.id.shloading).setVisibility(View.VISIBLE);
    }

    @Deprecated
    public void hideContentLoadingView() {
        if (getContainerView() != null && getContainerView().findViewById(R.id.shloading) != null)
            getContainerView().findViewById(R.id.shloading).setVisibility(View.GONE);
    }

    /**
     * 显示内容加载失败，全屏的
     */
    public void showLoadFailAndRetryView(View.OnClickListener onClickListener) {
        if (getContainerView() != null &&getContainerView().findViewById(R.id.loadFailAndRetry) != null) {
            hideContentLoadingView();
            getContainerView().findViewById(R.id.loadFailAndRetry).setVisibility(View.VISIBLE);
            getContainerView().findViewById(R.id.base_retry).setOnClickListener(onClickListener);
        }
    }

    /**
     * 用{@link #hideLoadingAndRetryView()}代替
     */
    @Deprecated
    public void hideLoadFailAndRetryView() {
        if (getContainerView() != null &&getContainerView().findViewById(R.id.loadFailAndRetry) != null)
            getContainerView().findViewById(R.id.loadFailAndRetry).setVisibility(View.GONE);
    }

    /**
     * 同时隐藏内容加载和加载失败重试view
     */
    public void hideLoadingAndRetryView() {
        hideContentLoadingView();
        hideLoadFailAndRetryView();
    }

    /**
     * 获取底部导航栏颜色
     *
     * @return
     */
    public int getNavigationBarColor() {
        if (getActivity() != null && !getActivity().isFinishing())
            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? getActivity().getWindow().getNavigationBarColor() : ContextCompat.getColor(IGetContext(), R.color.color_white);
        return 0;
    }
}